package cn.iocoder.yudao.module.handguard.tool.formula;

import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 公式服务策略工厂
 */
@Component
public class FormulaStrategyFactory implements ApplicationContextAware {

    /**
     * 公式方式策略map
     */
    private static final Map<String, IFormulaStrategy> FORMULA_STRATEGY_MAP = new ConcurrentHashMap<>();

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        // 返回实现IFormulaStrategy接口的策略bean
        Map<String, IFormulaStrategy> formulaBeanMap = applicationContext.getBeansOfType(IFormulaStrategy.class);
        formulaBeanMap.values().forEach(paymentBean -> {
            FORMULA_STRATEGY_MAP.put(paymentBean.getFormulaName(), paymentBean);
        });
    }

    /**
     * 根据具体的公式方式获取对应的公式服务
     *
     * @param formulaName 公式方式
     * @return IFormulaStrategy
     */
    public <T extends IFormulaStrategy> IFormulaStrategy getFormulaInstance(String formulaName) {
        return FORMULA_STRATEGY_MAP.get(formulaName);
    }
}
